package models;

import java.io.File;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;

import org.apache.commons.lang.StringUtils;

import play.libs.Codec;
import beans.PageBean;
import beans.TypeBean;
import utils.Config;
import utils.DateUtils;
import utils.SessionUtils;

/**
 *
 * @author Chen
 * 2014/9/23
 */
@Entity
@Table(name = "photo")
public class Photo extends BasicModel{

    public static final int SuperAdmin = 1;
    public static final int Admin = 1;
    public static final int user = 0;

    @Column(name = "name")
    public String name;

    @Column(name = "url")
    public String url;

    @Column(name = "title")
    public String title;

    @Column(name = "type")
    public int type;

    public String getRenderType(){
        return TypeBean.getString(this.type);
    }

    public static Photo addPhoto(String name,String title){
        Photo photo = new Photo();
        photo.name = name;
        photo.title = title;
        photo.type = SessionUtils.getLoginUser().authority;
        photo.url = Config.imagePath+name;
        photo.save();
        return photo;
    }
    

    public String getPhoto(){
        return "../"+this.url;
    }

    public String getOriginPhoto(){
        int index = this.url.indexOf("/");
        String originUrl = "file/originFile/"+this.url.substring(this.url.indexOf("/", index+1)+1);
        return "../"+originUrl;
    }

    public String getCurTime(){
        return DateUtils.getDateTimeStr(this.createTime);
    }

    public static void delById(String id){
        Photo photo = Photo.findById(id);
        photo.delete();
    }
    
    public static void deletePhoto(String id)
    {
    	if(StringUtils.isEmpty(id))
    	{
    		return ;
    	}
    	Photo photo = Photo.findById(id);
		if(photo != null)
		{
			String photoAdd = photo.url;
			File image = new File(photoAdd);
			if(image.exists())
			{
				image.delete();
			}
			photo.delete();
		}
    }

}
